﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Sunimage.Spjg.Common;

namespace Sunimage.Spjg.DAL
{
    public class NoteDa
    {
        /// <summary>
        /// Insert
        /// </summary>
        /// <param name="note"></param>
        public static void Insert(Note note)
        {
            Database db = DBHelper.GetDatabase();
            object[] pars = new object[]
            {
                note.CreateTime,
                note.Title,
                note.Content,
                note.CreatorId
            };
            try
            {
                note.Id = Convert.ToInt32(db.ExecuteScalar("Usp_InsertNote", pars));
            }
            catch (System.Data.SqlClient.SqlException sex)      // 只捕获SqlException，其余抛出继续传播
            {
                DBHelper.ParseSqlException(sex, false);
            }
        }
        public static void Update(Note note)
        {
            Database db = DBHelper.GetDatabase();
            object[] pars = new object[]
            {
                note.Id,
                note.CreateTime,
                note.Title,
                note.Content,
                note.CreatorId
            };
            db.ExecuteNonQuery("Usp_UpdateNote", pars);
        }

        public static void Delete(int id)
        {
            Database db = DBHelper.GetDatabase();

            db.ExecuteNonQuery("Usp_DeleteNote", id);
        }

        public static List<Note> GetAll()
        {
            Database db = DBHelper.GetDatabase();
            List<Note> notes = new List<Note>();
            IDataReader dataReader = null;

            dataReader = db.ExecuteReader("Usp_GetNoteList");

            using (dataReader)
            {
                while (dataReader.Read())
                {
                    notes.Add(Populate(dataReader));
                }
            }

            return notes;
        }

        private static Note Populate(IDataReader dataReader)
        {

            Note note = new Note();
            note.Id = dataReader.GetInt32(0);
            note.CreateTime = dataReader.GetDateTime(1);
            note.Title = dataReader.GetString(2);
            note.Content = dataReader.GetString(3);
            note.CreatorId = dataReader.GetInt32(4);

            return note;
        }
    }
}
